from rest_framework import serializers
from ..models import FaKuyouStaffMember
from datetime import datetime
from django.core.validators import RegexValidator


class FaKuyouStaffMemberSerializer(serializers.ModelSerializer):
    status_display = serializers.CharField(
        source='get_status_display',
        read_only=True,
        help_text='状态显示'
    )
    create_datetime = serializers.SerializerMethodField(
        help_text='创建时间'
    )
    update_datetime = serializers.SerializerMethodField(
        help_text='更新时间'
    )

    class Meta:
        model = FaKuyouStaffMember
        fields = '__all__'
        extra_kwargs = {
            'phone': {
                'validators': [
                    RegexValidator(
                        regex=r'^1[3-9]\d{9}$',
                        message='请输入正确的手机号码格式'
                    )
                ]
            }
        }

    def get_create_datetime(self, obj):
        if obj.createtime:
            return datetime.fromtimestamp(obj.createtime).strftime('%Y-%m-%d %H:%M:%S')
        return None

    def get_update_datetime(self, obj):
        if obj.updatetime:
            return datetime.fromtimestamp(obj.updatetime).strftime('%Y-%m-%d %H:%M:%S')
        return None

    def validate_men_code(self, value):
        """验证职员编号唯一性"""
        if self.instance and self.instance.men_code == value:
            return value

        if FaKuyouStaffMember.objects.filter(men_code=value).exists():
            raise serializers.ValidationError("该职员编号已存在")
        return value

    def validate(self, data):
        """数据验证"""
        # 手机号验证
        if 'phone' in data and data['phone']:
            if not data['phone'].isdigit() or len(data['phone']) != 11:
                raise serializers.ValidationError({
                    'phone': '请输入11位数字的手机号码'
                })

        return data